home *** CD-ROM | disk | FTP | other *** search
/ Kompuutteri K-CD 2002 #1 / K-CD_2002-01.iso / Delphi / INSTALL / program files / Borland / Delphi6 / Doc / Math.int < prev    next >
Encoding:
Text File  |  2001-05-22  |  18.3 KB  |  433 lines

  1.  
  2. { *********************************************************************** }
  3. {                                                                         }
  4. { Delphi / Kylix Cross-Platform Runtime Library                           }
  5. {                                                                         }
  6. { Copyright (c) 1996, 2001 Borland Software Corporation                   }
  7. {                                                                         }
  8. { *********************************************************************** }
  9.  
  10. unit Math;
  11.  
  12. { This unit contains high-performance arithmetic, trigonometric, logorithmic,
  13.   statistical, financial calculation and FPU routines which supplement the math
  14.   routines that are part of the Delphi language or System unit.
  15.  
  16.   References:
  17.   1) P.J. Plauger, "The Standard C Library", Prentice-Hall, 1992, Ch. 7.
  18.   2) W.J. Cody, Jr., and W. Waite, "Software Manual For the Elementary
  19.      Functions", Prentice-Hall, 1980.
  20.   3) Namir Shammas, "C/C++ Mathematical Algorithms for Scientists and Engineers",
  21.      McGraw-Hill, 1995, Ch 8.
  22.   4) H.T. Lau, "A Numerical Library in C for Scientists and Engineers",
  23.      CRC Press, 1994, Ch. 6.
  24.   5) "Pentium(tm) Processor User's Manual, Volume 3: Architecture
  25.      and Programming Manual", Intel, 1994
  26.  
  27.   Some of the functions, concepts or constants in this unit were provided by
  28.   Earl F. Glynn (www.efg2.com) and Ray Lischner (www.tempest-sw.com)
  29.  
  30.   All angle parameters and results of trig functions are in radians.
  31.  
  32.   Most of the following trig and log routines map directly to Intel 80387 FPU
  33.   floating point machine instructions.  Input domains, output ranges, and
  34.   error handling are determined largely by the FPU hardware.
  35.  
  36.   Routines coded in assembler favor the Pentium FPU pipeline architecture.
  37. }
  38.  
  39. {$N+,S-}
  40.  
  41. interface
  42.  
  43. uses SysUtils, Types;
  44.  
  45. const   { Ranges of the IEEE floating point types, including denormals }
  46.   MinSingle   =  1.5e-45;
  47.   MaxSingle   =  3.4e+38;
  48.   MinDouble   =  5.0e-324;
  49.   MaxDouble   =  1.7e+308;
  50.   MinExtended =  3.4e-4932;
  51.   MaxExtended =  1.1e+4932;
  52.   MinComp     = -9.223372036854775807e+18;
  53.   MaxComp     =  9.223372036854775807e+18;
  54.  
  55.   { The following constants should not be used for comparison, only
  56.     assignments. For comparison please use the IsNan and IsInfinity functions
  57.     provided below. }
  58.   NaN         =  0.0 / 0.0;
  59.   Infinity    =  1.0 / 0.0;
  60.   NegInfinity = -1.0 / 0.0;
  61.  
  62. { Trigonometric functions }
  63. function ArcCos(const X: Extended): Extended;  { IN: |X| <= 1  OUT: [0..PI] radians }
  64. function ArcSin(const X: Extended): Extended;  { IN: |X| <= 1  OUT: [-PI/2..PI/2] radians }
  65.  
  66. { ArcTan2 calculates ArcTan(Y/X), and returns an angle in the correct quadrant.
  67.   IN: |Y| < 2^64, |X| < 2^64, X <> 0   OUT: [-PI..PI] radians }
  68. function ArcTan2(const Y, X: Extended): Extended;
  69.  
  70. { SinCos is 2x faster than calling Sin and Cos separately for the same angle }
  71. procedure SinCos(const Theta: Extended; var Sin, Cos: Extended) register;
  72. function Tan(const X: Extended): Extended;
  73. function Cotan(const X: Extended): Extended;           { 1 / tan(X), X <> 0 }
  74. function Secant(const X: Extended): Extended;          { 1 / cos(X) }
  75. function Cosecant(const X: Extended): Extended;        { 1 / sin(X) }
  76. function Hypot(const X, Y: Extended): Extended;        { Sqrt(X**2 + Y**2) }
  77.  
  78. { Angle unit conversion routines }
  79. function RadToDeg(const Radians: Extended): Extended;  { Degrees := Radians * 180 / PI }
  80. function RadToGrad(const Radians: Extended): Extended; { Grads := Radians * 200 / PI }
  81. function RadToCycle(const Radians: Extended): Extended;{ Cycles := Radians / 2PI }
  82.  
  83. function DegToRad(const Degrees: Extended): Extended;  { Radians := Degrees * PI / 180}
  84. function DegToGrad(const Degrees: Extended): Extended;
  85. function DegToCycle(const Degrees: Extended): Extended;
  86.  
  87. function GradToRad(const Grads: Extended): Extended;   { Radians := Grads * PI / 200 }
  88. function GradToDeg(const Grads: Extended): Extended;
  89. function GradToCycle(const Grads: Extended): Extended;
  90.  
  91. function CycleToRad(const Cycles: Extended): Extended; { Radians := Cycles * 2PI }
  92. function CycleToDeg(const Cycles: Extended): Extended;
  93. function CycleToGrad(const Cycles: Extended): Extended;
  94.  
  95. { Hyperbolic functions and inverses }
  96. function Cot(const X: Extended): Extended;             { simply calls Cotan }
  97. function Sec(const X: Extended): Extended;             { simply calls Secant }
  98. function Csc(const X: Extended): Extended;             { simply calls Cosecant }
  99. function Cosh(const X: Extended): Extended;
  100. function Sinh(const X: Extended): Extended;
  101. function Tanh(const X: Extended): Extended;
  102. function CotH(const X: Extended): Extended;
  103. function SecH(const X: Extended): Extended;
  104. function CscH(const X: Extended): Extended;
  105. function ArcCot(const X: Extended): Extended;
  106. function ArcSec(const X: Extended): Extended;
  107. function ArcCsc(const X: Extended): Extended;
  108. function ArcCosh(const X: Extended): Extended;         { IN: X >= 1 }
  109. function ArcSinh(const X: Extended): Extended;
  110. function ArcTanh(const X: Extended): Extended;         { IN: |X| <= 1 }
  111. function ArcCotH(const X: Extended): Extended;
  112. function ArcSecH(const X: Extended): Extended;
  113. function ArcCscH(const X: Extended): Extended;
  114.  
  115. { Logorithmic functions }
  116. function LnXP1(const X: Extended): Extended; { Ln(X + 1), accurate for X near zero }
  117. function Log10(const X: Extended): Extended;                    { Log base 10 of X }
  118. function Log2(const X: Extended): Extended;                      { Log base 2 of X }
  119. function LogN(const Base, X: Extended): Extended;                { Log base N of X }
  120.  
  121. { Exponential functions }
  122.  
  123. { IntPower: Raise base to an integral power.  Fast. }
  124. function IntPower(const Base: Extended; const Exponent: Integer): Extended register;
  125.  
  126. { Power: Raise base to any power.
  127.   For fractional exponents, or |exponents| > MaxInt, base must be > 0. }
  128. function Power(const Base, Exponent: Extended): Extended;
  129.  
  130. { Miscellaneous Routines }
  131.  
  132. { Frexp:  Separates the mantissa and exponent of X. }
  133. procedure Frexp(const X: Extended; var Mantissa: Extended; var Exponent: Integer) register;
  134.  
  135. { Ldexp: returns X*2**P }
  136. function Ldexp(const X: Extended; const P: Integer): Extended register;
  137.  
  138. { Ceil: Smallest integer >= X, |X| < MaxInt }
  139. function Ceil(const X: Extended):Integer;
  140.  
  141. { Floor: Largest integer <= X,  |X| < MaxInt }
  142. function Floor(const X: Extended): Integer;
  143.  
  144. { Poly: Evaluates a uniform polynomial of one variable at value X.
  145.     The coefficients are ordered in increasing powers of X:
  146.     Coefficients[0] + Coefficients[1]*X + ... + Coefficients[N]*(X**N) }
  147. function Poly(const X: Extended; const Coefficients: array of Double): Extended;
  148.  
  149. {-----------------------------------------------------------------------
  150. Statistical functions.
  151.  
  152. Common commercial spreadsheet macro names for these statistical and
  153. financial functions are given in the comments preceding each function.
  154. -----------------------------------------------------------------------}
  155.  
  156. { Mean:  Arithmetic average of values.  (AVG):  SUM / N }
  157. function Mean(const Data: array of Double): Extended;
  158.  
  159. { Sum: Sum of values.  (SUM) }
  160. function Sum(const Data: array of Double): Extended register;
  161. function SumInt(const Data: array of Integer): Integer register;
  162. function SumOfSquares(const Data: array of Double): Extended;
  163. procedure SumsAndSquares(const Data: array of Double;
  164.   var Sum, SumOfSquares: Extended) register;
  165.  
  166. { MinValue: Returns the smallest signed value in the data array (MIN) }
  167. function MinValue(const Data: array of Double): Double;
  168. function MinIntValue(const Data: array of Integer): Integer;
  169.  
  170. function Min(const A, B: Integer): Integer; overload;
  171. function Min(const A, B: Int64): Int64; overload;
  172. function Min(const A, B: Single): Single; overload;
  173. function Min(const A, B: Double): Double; overload;
  174. function Min(const A, B: Extended): Extended; overload;
  175.  
  176. { MaxValue: Returns the largest signed value in the data array (MAX) }
  177. function MaxValue(const Data: array of Double): Double;
  178. function MaxIntValue(const Data: array of Integer): Integer;
  179.  
  180. function Max(const A, B: Integer): Integer; overload;
  181. function Max(const A, B: Int64): Int64; overload;
  182. function Max(const A, B: Single): Single; overload;
  183. function Max(const A, B: Double): Double; overload;
  184. function Max(const A, B: Extended): Extended; overload;
  185.  
  186. { Standard Deviation (STD): Sqrt(Variance). aka Sample Standard Deviation }
  187. function StdDev(const Data: array of Double): Extended;
  188.  
  189. { MeanAndStdDev calculates Mean and StdDev in one call. }
  190. procedure MeanAndStdDev(const Data: array of Double; var Mean, StdDev: Extended);
  191.  
  192. { Population Standard Deviation (STDP): Sqrt(PopnVariance).
  193.   Used in some business and financial calculations. }
  194. function PopnStdDev(const Data: array of Double): Extended;
  195.  
  196. { Variance (VARS): TotalVariance / (N-1). aka Sample Variance }
  197. function Variance(const Data: array of Double): Extended;
  198.  
  199. { Population Variance (VAR or VARP): TotalVariance/ N }
  200. function PopnVariance(const Data: array of Double): Extended;
  201.  
  202. { Total Variance: SUM(i=1,N)[(X(i) - Mean)**2] }
  203. function TotalVariance(const Data: array of Double): Extended;
  204.  
  205. { Norm:  The Euclidean L2-norm.  Sqrt(SumOfSquares) }
  206. function Norm(const Data: array of Double): Extended;
  207.  
  208. { MomentSkewKurtosis: Calculates the core factors of statistical analysis:
  209.   the first four moments plus the coefficients of skewness and kurtosis.
  210.   M1 is the Mean.  M2 is the Variance.
  211.   Skew reflects symmetry of distribution: M3 / (M2**(3/2))
  212.   Kurtosis reflects flatness of distribution: M4 / Sqr(M2) }
  213. procedure MomentSkewKurtosis(const Data: array of Double;
  214.   var M1, M2, M3, M4, Skew, Kurtosis: Extended);
  215.  
  216. { RandG produces random numbers with Gaussian distribution about the mean.
  217.   Useful for simulating data with sampling errors. }
  218. function RandG(Mean, StdDev: Extended): Extended;
  219.  
  220. {-----------------------------------------------------------------------
  221. General/Misc use functions
  222. -----------------------------------------------------------------------}
  223.  
  224. { Extreme testing }
  225.  
  226. // Like a infinity, a NaN double value has an exponent of 7FF, but the NaN
  227. // values have a fraction field that is not 0.
  228. function IsNan(const AValue: Double): Boolean;
  229.  
  230. // Like a NaN, an infinity double value has an exponent of 7FF, but the
  231. // infinity values have a fraction field of 0. Infinity values can be positive
  232. // or negative, which is specified in the high-order, sign bit.
  233. function IsInfinite(const AValue: Double): Boolean;
  234.  
  235. { Simple sign testing }
  236.  
  237. type
  238.   TValueSign = -1..1;
  239.  
  240. const
  241.   NegativeValue = Low(TValueSign);
  242.   ZeroValue = 0;
  243.   PositiveValue = High(TValueSign);
  244.  
  245. function Sign(const AValue: Integer): TValueSign; overload;
  246. function Sign(const AValue: Int64): TValueSign; overload;
  247. function Sign(const AValue: Double): TValueSign; overload;
  248.  
  249. { CompareFloat & SameFloat: If epsilon is not given (or is zero) we will
  250.   attempt to compute a reasonable one based on the percision of the floating
  251.   point type used. }
  252.  
  253. function CompareValue(const A, B: Extended; Epsilon: Extended = 0): TValueRelationship; overload;
  254. function CompareValue(const A, B: Double; Epsilon: Double = 0): TValueRelationship; overload;
  255. function CompareValue(const A, B: Single; Epsilon: Single = 0): TValueRelationship; overload;
  256. function CompareValue(const A, B: Integer): TValueRelationship; overload;
  257. function CompareValue(const A, B: Int64): TValueRelationship; overload;
  258.  
  259. function SameValue(const A, B: Extended; Epsilon: Extended = 0): Boolean; overload;
  260. function SameValue(const A, B: Double; Epsilon: Double = 0): Boolean; overload;
  261. function SameValue(const A, B: Single; Epsilon: Single = 0): Boolean; overload;
  262.  
  263. { IsZero: These will return true if the given value is zero (or very very very
  264.   close to it). }
  265.  
  266. function IsZero(const A: Extended; Epsilon: Extended = 0): Boolean; overload;
  267. function IsZero(const A: Double; Epsilon: Double = 0): Boolean; overload;
  268. function IsZero(const A: Single; Epsilon: Single = 0): Boolean; overload;
  269.  
  270. { Easy to use conditional functions }
  271.  
  272. function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer = 0): Integer; overload;
  273. function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64 = 0): Int64; overload;
  274. function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double = 0.0): Double; overload;
  275.  
  276. { Various random functions }
  277.  
  278. function RandomRange(const AFrom, ATo: Integer): Integer;
  279. function RandomFrom(const AValues: array of Integer): Integer; overload;
  280. function RandomFrom(const AValues: array of Int64): Int64; overload;
  281. function RandomFrom(const AValues: array of Double): Double; overload;
  282.  
  283. { Range testing functions }
  284.  
  285. function InRange(const AValue, AMin, AMax: Integer): Boolean; overload;
  286. function InRange(const AValue, AMin, AMax: Int64): Boolean; overload;
  287. function InRange(const AValue, AMin, AMax: Double): Boolean; overload;
  288.  
  289. { Range truncation functions }
  290.  
  291. function EnsureRange(const AValue, AMin, AMax: Integer): Integer; overload;
  292. function EnsureRange(const AValue, AMin, AMax: Int64): Int64; overload;
  293. function EnsureRange(const AValue, AMin, AMax: Double): Double; overload;
  294.  
  295. { 16 bit integer division and remainder in one operation }
  296.  
  297. procedure DivMod(Dividend: Integer; Divisor: Word;
  298.   var Result, Remainder: Word);
  299.  
  300.  
  301. { Round to a specific digit or power of ten }
  302. { ADigit has a valid range of 37 to -37.  Here are some valid examples
  303.   of ADigit values...
  304.    3 = 10^3  = 1000   = thousand's place
  305.    2 = 10^2  =  100   = hundred's place
  306.    1 = 10^1  =   10   = ten's place
  307.   -1 = 10^-1 = 1/10   = tenth's place
  308.   -2 = 10^-2 = 1/100  = hundredth's place
  309.   -3 = 10^-3 = 1/1000 = thousandth's place }
  310.  
  311. type
  312.   TRoundToRange = -37..37;
  313.  
  314. function RoundTo(const AValue: Double; const ADigit: TRoundToRange): Double;
  315.  
  316. { This variation of the RoundTo function follows the asymmetric arthmetic
  317.   rounding algorithm (if Frac(X) < .5 then return X else return X + 1).  This
  318.   function defaults to rounding to the hundredth's place (cents). }
  319.  
  320. function SimpleRoundTo(const AValue: Double; const ADigit: TRoundToRange = -2): Double;
  321.  
  322. {-----------------------------------------------------------------------
  323. Financial functions.  Standard set from Quattro Pro.
  324.  
  325. Parameter conventions:
  326.  
  327. From the point of view of A, amounts received by A are positive and
  328. amounts disbursed by A are negative (e.g. a borrower's loan repayments
  329. are regarded by the borrower as negative).
  330.  
  331. Interest rates are per payment period.  11% annual percentage rate on a
  332. loan with 12 payments per year would be (11 / 100) / 12 = 0.00916667
  333.  
  334. -----------------------------------------------------------------------}
  335.  
  336. type
  337.   TPaymentTime = (ptEndOfPeriod, ptStartOfPeriod);
  338.  
  339. { Double Declining Balance (DDB) }
  340. function DoubleDecliningBalance(const Cost, Salvage: Extended;
  341.   Life, Period: Integer): Extended;
  342.  
  343. { Future Value (FVAL) }
  344. function FutureValue(const Rate: Extended; NPeriods: Integer; const Payment,
  345.   PresentValue: Extended; PaymentTime: TPaymentTime): Extended;
  346.  
  347. { Interest Payment (IPAYMT)  }
  348. function InterestPayment(const Rate: Extended; Period, NPeriods: Integer;
  349.   const PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  350.  
  351. { Interest Rate (IRATE) }
  352. function InterestRate(NPeriods: Integer; const Payment, PresentValue,
  353.   FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  354.  
  355. { Internal Rate of Return. (IRR) Needs array of cash flows. }
  356. function InternalRateOfReturn(const Guess: Extended;
  357.   const CashFlows: array of Double): Extended;
  358.  
  359. { Number of Periods (NPER) }
  360. function NumberOfPeriods(const Rate: Extended; Payment: Extended;
  361.   const PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  362.  
  363. { Net Present Value. (NPV) Needs array of cash flows. }
  364. function NetPresentValue(const Rate: Extended; const CashFlows: array of Double;
  365.   PaymentTime: TPaymentTime): Extended;
  366.  
  367. { Payment (PAYMT) }
  368. function Payment(Rate: Extended; NPeriods: Integer; const PresentValue,
  369.   FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  370.  
  371. { Period Payment (PPAYMT) }
  372. function PeriodPayment(const Rate: Extended; Period, NPeriods: Integer;
  373.   const PresentValue, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  374.  
  375. { Present Value (PVAL) }
  376. function PresentValue(const Rate: Extended; NPeriods: Integer;
  377.   const Payment, FutureValue: Extended; PaymentTime: TPaymentTime): Extended;
  378.  
  379. { Straight Line depreciation (SLN) }
  380. function SLNDepreciation(const Cost, Salvage: Extended; Life: Integer): Extended;
  381.  
  382. { Sum-of-Years-Digits depreciation (SYD) }
  383. function SYDDepreciation(const Cost, Salvage: Extended; Life, Period: Integer): Extended;
  384.  
  385. type
  386.   EInvalidArgument = class(EMathError) end;
  387.  
  388. {-----------------------------------------------------------------------
  389. FPU exception/precision/rounding management
  390.  
  391. The following functions allow you to control the behavior of the FPU.  With
  392. them you can control what constutes an FPU exception, what the default
  393. precision is used and finally how rounding is handled by the FPU.
  394.  
  395. -----------------------------------------------------------------------}
  396.  
  397. type
  398.   TFPURoundingMode = (rmNearest, rmDown, rmUp, rmTruncate);
  399.  
  400. { Return the current rounding mode }
  401. function GetRoundMode: TFPURoundingMode;
  402.  
  403. { Set the rounding mode and return the old mode }
  404. function SetRoundMode(const RoundMode: TFPURoundingMode): TFPURoundingMode;
  405.  
  406. type
  407.   TFPUPrecisionMode = (pmSingle, pmReserved, pmDouble, pmExtended);
  408.  
  409. { Return the current precision control mode }
  410. function GetPrecisionMode: TFPUPrecisionMode;
  411.  
  412. { Set the precision control mode and return the old one }
  413. function SetPrecisionMode(const Precision: TFPUPrecisionMode): TFPUPrecisionMode;
  414.  
  415. type
  416.   TFPUException = (exInvalidOp, exDenormalized, exZeroDivide,
  417.                    exOverflow, exUnderflow, exPrecision);
  418.   TFPUExceptionMask = set of TFPUException;
  419.  
  420. { Return the exception mask from the control word.
  421.   Any element set in the mask prevents the FPU from raising that kind of
  422.   exception.  Instead, it returns its best attempt at a value, often NaN or an
  423.   infinity. The value depends on the operation and the current rounding mode. }
  424. function GetExceptionMask: TFPUExceptionMask;
  425.  
  426. { Set a new exception mask and return the old one }
  427. function SetExceptionMask(const Mask: TFPUExceptionMask): TFPUExceptionMask;
  428.  
  429. { Clear any pending exception bits in the status word }
  430. procedure ClearExceptions;
  431.  
  432. implementation
  433.